package com.qbw.app.module.user.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.UserManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.http.okhttp.HttpTask;
import com.lib.util.DateTimeUtil;
import com.lib.util.NetUtil;
import com.lib.util.ResUtil;
import com.lib.util.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.qbw.app.Config;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.XApplication;
import com.qbw.app.databinding.UserActivityLoginBinding;
import com.qbw.app.model.BaseModel;
import com.qbw.app.model.BaseResponse;
import com.qbw.app.model.Country;
import com.qbw.app.model.User;
import com.qbw.app.model.Vehicle;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.activity.SelectCountryAreaActivity;
import com.qbw.app.module.common.util.CountryUtil;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.main.activity.MainActivity;
import com.qbw.app.module.vehicle.activity.VehicleAddActivity;
import com.qbw.app.module.vehicle.activity.VehicleBindByScanActivity;
import com.qbw.app.request.impl.UserRequest;
import com.qbw.app.request.impl.VehicleRequest;
import com.qbw.core.observable.ObservableString;
import com.qbw.core.okhttp.JsonCallback;
import com.qbw.spm.P;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;

import static com.qbw.app.request.impl.UserRequest.METHOD_UPDATE_INFO;


/*
 *
 * @author QBW
 * @date 2019/8/15
 */
public class UserLoginActivity extends CommonActivity<UserActivityLoginBinding> {

    private Country mSelectedCountry;
    private final int REQUEST_CODE_SELECT_COUNTRY_AREA = 1;

    private ObservableString mCountryArea = new ObservableString();
    private ObservableString mPhone = new ObservableString();
    private ObservableString mPassword = new ObservableString();
    private ObservableString mError = new ObservableString();

    public static void start(Context context) {
        Intent intent = new Intent(context, UserLoginActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.user_activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGeneralManager.getUserManager().logout();
        mBinding.title.setListener(this);
        String ca = P.getString(Constant.KEY_LAST_LOGIN_COUNTRY_AREA);
        if (!TextUtils.isEmpty(ca)) {
            mCountryArea.setValue(ca);
        }
        mPhone.setValue(P.getString(Constant.KEY_LAST_LOGIN_PHONE));
        mBinding.setCountryArea(mCountryArea);
        mBinding.setPhone(mPhone);
        mBinding.setPassword(mPassword);
        mBinding.setError(mError);
        mBinding.executePendingBindings();
        mBinding.tvCountryAreaValue.setOnClickListener(this);
        mBinding.tvForgetPassword.setOnClickListener(this);
        mBinding.tvLogin.setOnClickListener(this);
        mBinding.ivEtDel.setOnClickListener(this);
        if (!TextUtils.isEmpty(mCountryArea.getValue())) {
            Country.Response response = Country.Response.fromJson(P.getString(Constant.KEY_ALL_COUNTRYS));
            if (response != null) {
                mSelectedCountry = response.getCountry(mCountryArea.getValue());
            }
            mBinding.etPassword.requestFocus();
        } else {
            int cid = CountryUtil.getCountryId();
            Country.Response response = Country.Response.fromJson(P.getString(Constant.KEY_ALL_COUNTRYS));
            if (response != null) {
                mSelectedCountry = response.getCountry(cid);
                if (mSelectedCountry == null) {
                    if (response.size() > 0) {
                        mSelectedCountry = response.getData().get(0);
                        mCountryArea.setValue(mSelectedCountry.getTelCode());
                    }
                } else {
                    mCountryArea.setValue(mSelectedCountry.getTelCode());
                }
            }
        }

    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == R.id.tv_login) {
            if (TextUtils.isEmpty(mCountryArea.getValue()) || mSelectedCountry == null) {
                mError.setValue(ResUtil.getString(R.string.please_select_country_area));
                return;
            } else if (!Pattern.compile(mSelectedCountry.getPhoneJs())
                               .matcher(mPhone.getValue())
                               .matches()) {
                mError.setValue(ResUtil.getString(R.string.invalid_phone_format));
                return;
            } else if (TextUtils.isEmpty(mPassword.getValue())) {
                mError.setValue(ResUtil.getString(R.string.input_password));
                return;
            }
            mGeneralManager.getRequestManager()
                           .getUserRequest()
                           .login(mCountryArea.getValue(),
                                  mPhone.getValue(),
                                  mPassword.getValue(),
                                  this)
                           .execute();
        } else if (vid == R.id.tv_country_area_value) {
            SelectCountryAreaActivity.startForResult(this, REQUEST_CODE_SELECT_COUNTRY_AREA);
        } else if (vid == R.id.tv_forget_password) {
            UserResetPasswordActivity.startActivity(this, mCountryArea.getValue(), mPhone.getValue());
        }else if(vid == R.id.iv_et_del){
            mPhone.setValue("");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_SELECT_COUNTRY_AREA) {
                Country country = (Country) data.getSerializableExtra(Constant.KEY_SELECTED_COUNTRY);
                mCountryArea.setValue(country.getTelCode());
                mSelectedCountry = country;
            }
        }
    }


    // 更新极光注册ID
    private void  updatePushInfo(){
        JSONObject jb = new JSONObject();
        try {
            jb.put("deviceToken", JPushInterface.getRegistrationID(XApplication.getInstance()));
            jb.put("timestamp",  DateTimeUtil.getServerCurrentTimeMillis() + "");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkGo.<BaseModel>post( Config.getUrl()+"/"+METHOD_UPDATE_INFO)
                .tag(this)
                .upJson(jb)
                .execute(new JsonCallback<BaseModel>() {
                    @Override
                    public void onSuccess(Response<BaseModel> response) {

                        mGeneralManager.getRequestManager().getVehicleRequest().getVehicleList(UserLoginActivity.this).execute();
                    }

                    @Override
                    public void onError(Response<BaseModel> response) {
                        super.onError(response);
                        closeLoadingDialog();

                    }
                });
    }

    @Override
    public void onHttpStart(HttpTask httpTask) {
        super.onHttpStart(httpTask);
        String method = httpTask.getMethod();
        if (method.equals(UserRequest.METHOD_LOGIN)) {
            showLoadingDialog("");
        }
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(UserRequest.METHOD_LOGIN)) {

//            mGeneralManager.getRequestManager()
//                           .getUserRequest()
//                           .updateInfo(JPushInterface.getRegistrationID(this), "", "", "", null)
//                           .execute();
            updatePushInfo();

        }else if (method.equals(METHOD_UPDATE_INFO)) {
//            ToastUtil.showToast(this,"更新用户信息成功");
//            mGeneralManager.getRequestManager().getVehicleRequest().getVehicleList(this).execute();
        }  else if (method.equals(VehicleRequest.METHOD_VEHICLE_LIST)) {
            closeLoadingDialog();
            Vehicle.Response res = (Vehicle.Response) entity;
            if (res.getData().isEmpty()) {
                //没有车辆
                VehicleBindByScanActivity.startActivity(this, VehicleBindByScanActivity.TYPE_FROM_NO_VEHICLE);
            } else {
                MainActivity.start(this);
            }
            finishAffinity();
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        message = HttpRequestUtil.getMessage(errorCode, message);
        String method = httpTask.getMethod();
        closeLoadingDialog();
        if (method.equals(UserRequest.METHOD_LOGIN)) {

            if (NetUtil.isNetAvailable(this)) {
                mError.setValue(message);
            } else {
                UniversalToastUtil.showFailedIconToast(message);
            }
        } else if (method.equals(VehicleRequest.METHOD_VEHICLE_LIST)) {
            UniversalToastUtil.showFailedIconToast(message);
        }else if (method.equals(METHOD_UPDATE_INFO)) {
            ToastUtil.showToast(this,"用户信息请求失败");
//            mGeneralManager.getRequestManager().getVehicleRequest().getVehicleList(this).execute();
        }
    }
}
